from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from goods.models import SPU, GoodsCategory, Brand
from meiduo_admin.serializer.brands import BrandSerializer
from meiduo_admin.serializer.skus import GoodsCategorySerializer
from meiduo_admin.serializer.specs import SPUSerializer
from meiduo_admin.utils import PageNum



from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.decorators import action
from django.conf import settings
from rest_framework.response import Response
# spu 表的增删改查
class SPUView(ModelViewSet):
    # 指定权限
    permission_classes = [IsAdminUser]
    # 指定序列化器
    serializer_class = SPUSerializer
    # 指定查询集
    queryset = SPU.objects.all()
    # 指定分页器
    pagination_class = PageNum

    # 获取品牌表信息
    def simple(self,request):
        # 查询所有品牌信息
        brands = Brand.objects.all()
        # 序列化返回
        ser = BrandSerializer(brands,many=True)
        return Response(ser.data)

    # 获取一级分类信息
    def channel(self,request):
        # 获取一级分类
        data = GoodsCategory.objects.filter(parent_id=None)
        # 序列化返回
        ser = GoodsCategorySerializer(data,many=True)
        return Response(ser.data)

    # 获取二级三级分类信息
    def channels(self,request,pk):
        # 获取二级三级分类
        datas = GoodsCategory.objects.filter(parent_id=pk)
        # 序列化返回
        ser = GoodsCategorySerializer(datas, many=True)
        return Response(ser.data)


    def image(self, request):
        # 获取要保存的图片对象
        data = request.FILES.get('image')
        # 验证图片数据
        if data is None:
            return Response(status=500)
        # 建立fastFDS 的链接对象
        client = Fdfs_client(settings.FASTDFS_CONF)
        # 上传图片数据
        res = client.upload_by_buffer(data.read())
        # 判断上传状态
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传图片失败')
        # 获取上传的图片路径
        image_url = res['Remote file_id']

        # 结果返回
        return Response(
            {
                'img_url': settings.FDFS_URL + image_url
            },

            status=201
        )



